var xlsx = require('node-xlsx');
var fs = require('fs');
const path = require('path');
var Json2csvParser = require('json2csv').Parser;
const nodeFields = ['TableName', 'Id', 'TableNo', 'TableIndex'];
const edgeFields = ['Source', 'Target', 'Weight', 'Season'];

const root = path.resolve(__dirname, '../');
const xlsxFilePath = path.join(root, 'assets/tablenode.xlsx');
const csvNodesFilePath = path.join(root, 'assets/csv/tables.csv');
const csvEdgeFilePath = path.join(root, 'assets/csv/edges.csv');
var sheets = xlsx.parse(xlsxFilePath);
var arr = [];
//sheets是一个数组，数组中的每一项对应test.xlsx这个文件里的多个表格，如sheets[0]对应test.xlsx里的“测试参数”这个表格，sheets[1]对应Sheet2这个表格
sheets.forEach(function (sheet) {
    var newSheetsArr = [];
    //sheet是一个json对象，格式为{name:"测试参数",data:[]},我们想要的数据就存储在data里
    for (var i = 3; i < sheet["data"].length; i++) { //excel文件里的表格一般有标题所以不一定从0开始
        var row = sheet['data'][i];
        if (row && row.length > 0) {
            newSheetsArr.push({
                TableName: String(row[1]) && String(row[1]).replace(/\s/g, ''), //部分文本尾部可能会有空格，要去除
                Id: String(row[2]),
                TableNo: String(row[3]),
                TableIndex: String(row[4]),
            });
        }
    }
    csv(newSheetsArr)
    mockEdge(newSheetsArr)
});
function csv(arr) {
    try {
        const json2csvParser = new Json2csvParser({ nodeFields });
        var csv = json2csvParser.parse(arr);
        fs.writeFile(csvNodesFilePath, csv, (msg) => {
            console.log('!!csv generated successfully!!');
        });
    } catch (err) {
        console.error("convert", err, err.stack);
    }
}
function mockEdge(arr) {
    console.dir(arr);
    const result = [];
    const length = arr.length;
    const newArr = arr.map((value, index) => {
        const cur = [];
        if (index % 2 === 0) { return cur }
        let hashNumArr = new Array(length).fill('').map((v, i) => i).filter((v, i) => i !== index);
        let hashLen = hashNumArr.length;
        for (let i = 0; i < hashLen - 1;) {
            let suiji = Math.floor(Math.random() * 10);
            if (suiji + i > hashLen - 1) {
                break;
            } else {
                cur.push({
                    // Source,Target,Weight,Season
                    Source: value.Id,
                    Target: arr[i + suiji].Id,
                    Weight: Math.floor(Math.random() * 10 + 1),
                    Season: '4'
                })
            }
            i = i + suiji;
        }
        return cur;
    })
    try {
        const json2csvParser = new Json2csvParser({ edgeFields });
        var csv = json2csvParser.parse(newArr.flat());
        fs.writeFile(csvEdgeFilePath, csv, (msg) => {
            console.log('!!csv generated successfully!!');
        });
    } catch (err) {
        console.error("convert", err, err.stack);
    }
}　